//
//  huiyichauxnViewController.m
//  gangquOASystem
//
//  Created by michael on 2018/8/17.
//  Copyright © 2018年 czd. All rights reserved.
//
#import "SelectAlert.h"

#import "huiyishiViewController.h"
#import "UIView+ViewController.h"
#import "PickerChoiceView.h"
#import "huiyichauxnViewController.h"
#import "hysxqViewController.h"
#import "HYSlistViewController.h"
#import "GZZBlistViewController.h"
#import "ggxqViewController.h"
#import "LGLSearchBar.h"
#import "daibanTableViewCell.h"
#import "detailViewController.h"
#import "yjTableViewCell.h"
#import "dzTableViewCell.h"
#import "GDataDefines.h"
#import "UnDoneModel.h"
#import "OADetailViewController.h"
#import "OADetailDisPatchController.h"
#import "OAUnDoneListCell.h"
#import "ckUnDonelistCell.h"
#import "dzggViewController.h"
@interface huiyichauxnViewController ()<TFPickerDelegate>
@property(nonatomic,strong)NSMutableArray * dataArray;
@property(nonatomic,assign)int totalCounts; //总条数
@property(nonatomic,assign)int currentPage; //当前页
@property(nonatomic,strong)NSDictionary * adic;
@property (nonatomic,strong)NSString *searchstr;
@end

@implementation huiyichauxnViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
//     UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithTitle:@"新建"style:UIBarButtonItemStylePlain target:self action:@selector(rightButtonAction)];
// self.navigationItem.rightBarButtonItem = item1;
// [self _iniview];
            [self loaddata];

_tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 40, KScreenWidth,self.view.height-kTopHeight-44-LL_TabbarSafeBottomMargin-40) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        self.tableView.backgroundColor = [UIColor colorWithHexString:@"efeff4"];
    _tableView.separatorStyle = NO;

    self.tableView.delegate = self;
    self.tableView.dataSource =self;
    [self.view addSubview:_tableView];
   // self.TableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshOADetailData" object:nil];
                     __weak typeof(self) weakSelf = self;

    [self.tableView addHeaderWithCallback:^{
            weakSelf.currentPage = 1;

    if([weakSelf.isSearching isEqualToString:@"yes"]){
         [weakSelf loadSearchData];

    }else{

        [self loadData]; //加载网络数据
        }
    }];
    [self.tableView headerBeginRefreshing];
    
    [self.tableView addFooterWithCallback:^{
        if ((self.currentPage - 1)*KPageSize < self.totalCounts ){
        if([weakSelf.isSearching isEqualToString:@"yes"]){
         [weakSelf loadSearchMore];

    }else{

                 [weakSelf loadMore];
 //加载网络数据
        }
        
        
        
        }else{
        
            [self.tableView footerEndRefreshing];
            [self.view makeToast:@"没有更多了"];
    
        }
       
    }];
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"refreshData" object:nil];
//                  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(xinjian) name:@"xinjian" object:nil];

}
- (void)loadSearchData{
    __weak typeof(self) weakSelf = self;
_currentPage = 1;
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"type":_searchstr},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
     [HttpTools requestWithURL:@"exchassistant" arrays:array method:@"selectapplymeetroomPage" success:^(id JSON) {
    NSLog(@"%@",JSON);

      if (self.currentPage ==1) {
            [self.dataArray removeAllObjects];
        }
      _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
                self.totalCounts =[JSON[@"number"] intValue];
if(JSON[@"number"]){
_titlename = [NSString stringWithFormat:@"会议室查询(%@)",JSON[@"number"] ];
 if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}else{
_titlename  = @"会议室查询";
  if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;
        
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
        
    } failure:^(NSError *error) {
        if (self.tableView.headerRefreshing) {
            [self.tableView headerEndRefreshing];
        }
        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];

}
- (void)loadSearchMore{
    __weak typeof(self) weakSelf = self;

NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"type":_searchstr},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
 [HttpTools requestWithURL:@"exchassistant" arrays:array method:@"FilesDispatchSearch" success:^(id JSON) {

       NSArray *array = JSON[@"data"];

 for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

   self.totalCounts =[JSON[@"number"] intValue];


        [weakSelf.tableView footerEndRefreshing];
        [weakSelf.tableView reloadData];
        weakSelf.currentPage++;

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
     
    } failure:^(NSError *error) {

        if (self.tableView.footerRefreshing) {
            [self.tableView footerEndRefreshing];
        }
    }];
}
- (void)loaddata{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId}];
[HttpTools requestWithURL:@"exchassistant" arrays:array method:@"getMeetroom" success:^(id JSON) {
NSLog(@"%@",JSON);
NSArray *array0 = JSON[@"data"];
NSMutableArray *muarray = [NSMutableArray array];
for (NSDictionary *dic in array0) {
    [muarray addObject:dic[@"gwFstword"]];
}
_array = muarray;
[self initview];
} failure:^(NSError *error) {
    
    
    }];




}
- (void)initview{
   _button1 = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, (kScreenWidth-20), 30)];
    [_button1 setTitle:@"请点击选择会议室查看"forState:UIControlStateNormal];

   [_button1 addTarget:self action:@selector(buttonAction1) forControlEvents:UIControlEventTouchUpInside];
          [_button1.layer setBorderColor:[UIColor blackColor].CGColor];
    [_button1.layer setBorderWidth:1];
 [_button1.layer setMasksToBounds:YES];
   [_button1 setTitleColor:[UIColor blackColor]forState:UIControlStateNormal];
        _button1.layer.cornerRadius = _button1.height/2;
//[_button1 setImage:[UIImage imageNamed:@"下拉@2x"] forState:UIControlStateNormal];
[_button1 layoutButtonWithEdgeInsetsStyle:MKButtonEdgeInsetsStyleRight
                        imageTitleSpace:10];
//    _button1.layer.shadowOffset = CGSizeMake(1,1);
//    _button1.layer.shadowOpacity = 0.3;
//    _button1.layer.shadowColor = [UIColor blackColor].CGColor;
    [self.view addSubview:_button1];

}
- (void)buttonAction1{
[SelectAlert showWithTitle:@"会议室选择" titles:_array selectIndex:^(NSInteger selectIndex) {
    } selectValue:^(NSString *selectValue) {
        _searchstr = selectValue;
    [_button1 setTitle:selectValue forState:UIControlStateNormal];
            self.currentPage = 1;
_isSearching = @"yes";
    [self loadSearchData];

    } showCloseButton:YES];
// PickerChoiceView *picker = [[PickerChoiceView alloc]initWithFrame:self.tableView.bounds];
//
//    picker.delegate = self;
////    picker.type = @"year";
//        picker.selectLb.text = @"会议室选择";
//        picker.customArr = _array;
//
//huiyishiViewController *vc = (huiyishiViewController *)self.view.ViewController;
//
//    [vc.view addSubview:picker];
}
- (void)PickerSelectorIndixString:(NSString *)str:(NSString *)type{

    
    _searchstirng = str;
    [_button1 setTitle:str forState:UIControlStateNormal];
            self.currentPage = 1;
_isSearching = @"yes";

 
 }
- (void)xinjian{
HYSViewController *vc = [[HYSViewController alloc]init];
[self.navigationController pushViewController:vc animated:YES];
}
- (void)viewWillAppear:(BOOL)animated{

// if (self.selectRowBlock) {
//  self.selectRowBlock(_titlename);
//  }


    [self.tableView headerBeginRefreshing];

}
#pragma mark 刷新数据
-(void)refreshData{
    
    self.currentPage = 1;
    [self loadData]; //加载网络数据
}

#pragma mark 加载网络数据
-(void)loadData{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    //requestWithURL
    [HttpTools requestWithURL:@"exchassistant" arrays:array method:@"meetroomPage" success:^(id JSON) {
    NSLog(@"%@",JSON);
        if (self.currentPage ==1) {
           [self.dataArray removeAllObjects];
        }
//         NSData *jsonData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
//    NSError *err;
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
//                                                        options:NSJSONReadingMutableContainers
//                                                          error:&err];
  _dataArray =   [NSMutableArray array];
        NSArray *array = JSON[@"data"];
                self.totalCounts =[JSON[@"number"] intValue];
if(JSON[@"number"]){
_titlename = [NSString stringWithFormat:@"会议室查询(%@)",JSON[@"number"] ];
   if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}else{
_titlename  = @"会议室查询";
  if (self.selectRowBlock) {
  self.selectRowBlock(_titlename);
  }
}
         for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];

        [self.tableView reloadData];
        [self.tableView headerEndRefreshing];
        self.currentPage++;
        if (self.dataArray.count ==0) {
        [self.view makeToast:@"暂时还没有会议室查询哦"];
        }
    } failure:^(NSError *error) {
     [self.TableView headerEndRefreshing];
        
    }];
 
}
#pragma mark 加载更多
-(void)loadMore{
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray * array = @[@{@"userId":userId},@{@"page":[NSString stringWithFormat:@"%ld",(long)self.currentPage]}];
    [HttpTools requestWithURL:@"exchassistant" arrays:array method:@"meetroomPage" success:^(id JSON) {
                NSArray *array = JSON[@"data"];

//        [self.dataArray addObjectsFromArray:[self getDataList:[JSON dataUsingEncoding:NSUTF8StringEncoding]]];
  for (NSDictionary *dic in array) {
    NSDictionary *dict = dic;
    [_dataArray addObject:dict];
    
}
_adic= JSON[@"display"];


        self.currentPage++;
                [self.tableView reloadData];

        [self.tableView footerEndRefreshing];
       
    } failure:^(NSError *error) {
         [self.tableView footerEndRefreshing];
    }];
    
}
//得到服务器返回数据中的标题
//传参数：一个服务器返回的二进制数据
-(NSMutableArray*)getDataList:(NSData*)data
{
    NSMutableArray * array = [NSMutableArray array];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData: data options:0 error:nil];
    //获取根节点（<交换 >）
    GDataXMLElement *rootElement = [doc rootElement];
    //获取根节点下的节点（数据）
    NSArray *dataArray= [rootElement elementsForName:@"数据"];
    for (GDataXMLElement * elemtenData in dataArray) {
    
        NSArray * subElement = [elemtenData elementsForName:@"数据要素"];
        for (GDataXMLElement *data in subElement) {
            UnDoneModel * model = [[UnDoneModel alloc] init];
            GDataXMLElement * signElement = [[data elementsForName:@"是否编辑"] objectAtIndex:0];
            
            GDataXMLElement * titleElement = [[data elementsForName:@"标题"] objectAtIndex:0];
            GDataXMLElement * timeElement = [[data elementsForName:@"接收时间"] objectAtIndex:0];
            GDataXMLElement * nameElement = [[data elementsForName:@"上一办理人"] objectAtIndex:0];
            GDataXMLElement * stateElement = [[data elementsForName:@"公文状态"] objectAtIndex:0];
            GDataXMLElement * formElement = [[data elementsForName:@"表单"] objectAtIndex:0];
            GDataXMLElement * fileIdElement = [[data elementsForName:@"标识"] objectAtIndex:0];
            model.isSign = [signElement stringValue];
            model.title = [titleElement stringValue];
            model.time = [timeElement stringValue];
            model.name = [nameElement stringValue];
            model.state = [stateElement stringValue];
            model.form = [formElement stringValue];
            model.fileId = [fileIdElement stringValue];
            [array addObject:model];
        }
    }
    
    NSArray *countArray= [rootElement elementsForName:@"控制"];
    for (GDataXMLElement * data in countArray) {
        GDataXMLElement * countElement = [[data elementsForName:@"条数"] objectAtIndex:0];
        NSString * counts = [countElement stringValue];
        self.totalCounts = [counts intValue];
    }
    
     self.title = [NSString stringWithFormat:@"会议室管理(%lu)",(unsigned long)self.totalCounts];
   
    return array;
}



//- (void)_initview{
//self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, kScreenHeight) style:UITableViewStylePlain];
//self.tableView.delegate = self;
//self.tableView.dataSource = self;
//    [self.view addSubview:self.tableView];
//
//
//
//}
#pragma mark UITableView dataScource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

 static NSString *CellIdentifier = @"Cell";

    daibanTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
  if (cell==nil) {
        cell=[[daibanTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
 NSDictionary *dic = self.dataArray[indexPath.row];
    cell.dic = dic;
    cell.adic = _adic;
    cell.number = [NSString stringWithFormat:@"%ld",(long)indexPath.row+1];
    return cell;




//     if (![model.isRead isEqualToString:@"1"]) {
//
// cell.contentView.backgroundColor = [UIColor colorWithRed:231/255.0 green:231/255.0 blue:231/255.0 alpha:1];
//        }
//        else{
//      cell.contentView.backgroundColor = [UIColor whiteColor];
//        }
 }

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSDictionary *dic = self.dataArray[indexPath.row];

//      ggxqViewController * detailVC = (ggxqViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"ggxq"];
//hysxqViewController *vc = [[hysxqViewController alloc]init];
      hysxqViewController * detailVC = (hysxqViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"hysxq"];

//vc.fileId =dic[@"unid"];
detailVC.type = @"HYS";

detailVC.fileId = dic[@"unid"];
//detailVC.type = @"dzgg";
//[self.navigationController pushViewController:vc animated:YES];

[self.navigationController pushViewController:detailVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UnDoneModel * model = self.dataArray[indexPath.row];
//    CGFloat height = 0;
//    CGFloat  titlesize  = [OAToolBox sizebyText:model.title font:14 minsWidth:80];
//    NSString * desstring = [NSString stringWithFormat:@"%@",model.time];
//    CGFloat dessize = [OAToolBox sizebyText:desstring font:13 minsWidth:60];;
//    height = titlesize + dessize + 20;
//    return  height;
     NSDictionary *dic = self.dataArray[indexPath.row];

    CGFloat  titleFloat  = [OAToolBox sizebyText:dic[@"subject"] font:14 minsWidth:60];

    return  titleFloat +40;

//return ( KScreenHeight-64)/10;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
